<?php

class RolesController extends Zend_Controller_Action
{

    /**
     * @var Lib_Flash
     */
    private $_flashMessenger = null;

    public function init()
    {
        $this->_helper->layout()->setLayout('admin-layout');
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        }

        $this->_flashMessenger = new Lib_Flash();
    }

    public function indexAction()
    {
        $rolesManager = new \Managers\Roles();
        $roles = $rolesManager->getList();
        
        $this->view->roles = $roles;

    }

    public function addAction()
    {
        $rolesManager = new \Managers\Roles();
        $params = $this->_request->getParams();

        if ($this->_request->isPost()) {
            $rolesManager->add($params);
            $this->_flashMessenger->addMessage('Role successfully added. Clear the cache to take changes.', Lib_Flash::NOTICE, Lib_Flash::PRE);
            $this->_redirect('/roles');
        }

        $default = $rolesManager->getPrivilegesByName();

        $resourcesManager = new \Managers\Resources();
        $resources = $resourcesManager->getList();

        $this->view->default = $default;
        $this->view->resources = $resources;

    }

    public function editAction()
    {
        $id = $this->_request->getParam('id');
        $rolesManager = new \Managers\Roles();
            
        if ($this->_request->isPost()) {
            $rolesManager->update($this->_request->getParams());
            $this->_flashMessenger->addMessage('Role successfully saved. Clear the cache to take changes.', Lib_Flash::NOTICE, Lib_Flash::PRE);
            $this->_redirect('/roles');
        }
        
        $role = $rolesManager->getById($id);
        $resourcesManager = new \Managers\Resources();
        $resources = $resourcesManager->getList();

        $default = $rolesManager->getPrivilegesByName();
        if(!$role['parent']) {
            $default = array();
        }

        $this->view->default = $default;
        $this->view->resources = $resources;
        $this->view->role = $role;

    }

    public function deleteAction() {

        $id = $this->_request->getParam('id');
        $rolesManager = new \Managers\Roles();
        $rolesManager->delete($id);
        $this->_flashMessenger->addMessage('Role successfully deleted. Clear the cache to take changes.', Lib_Flash::NOTICE, Lib_Flash::PRE);
        $this->_redirect('/roles');

    }
}
